package cn.JHai.rbac.interceptor;

import cn.JHai.rbac.RequiredPermission;
import cn.JHai.rbac.comm.CurrentUtil;
import cn.JHai.rbac.domain.Employee;
import cn.JHai.rbac.mapper.PermissionMapper;
import cn.JHai.rbac.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;


@Component
public class SecurityInterceptor implements HandlerInterceptor{

    //1.判读是否是超级管理员,是放行
    //如果是就方法没用注释放行
    //如果有注释注释在权限里，放行


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee current = CurrentUtil.getCurrent();
        Boolean admin = current.getAdmin();
        if(admin!=null&&admin){
            return true;
        }
        //System.out.println("1+++++++1==="+handler.getClass().getName());

        //System.out.println("11");
        if(handler instanceof HandlerMethod){
            System.out.println(handler.getClass().getName());
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequiredPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if(methodAnnotation==null){
                return true;
            }
            Set<String> expression = CurrentUtil.getExpression();
            //System.out.println(expression);
            //System.out.println(methodAnnotation.value()[1]);
            if(expression.contains(methodAnnotation.value()[1])){
                //System.out.println(methodAnnotation.value());
                return true;
            }
        }else{
            return true;
        }


        //request.getRequestDispatcher("/views\\common\\nopermission.jsp").forward(request,response);
        request.getRequestDispatcher("/common/nopermission").forward(request,response);
        return false;
    }
}
